package com.abu.messagems.listener;

import com.abu.messagems.utils.GeneratorCode;
import com.abu.messagems.utils.SmsTemplate;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.StringReader;
import java.util.concurrent.TimeUnit;

@Configuration
public class MListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SmsTemplate smsTemplate;

    private static final String PREFIX = "UMS.CODE";

    @RabbitListener(queuesToDeclare = @Queue(value = "USM.PHONE"))
    public void sendMsg(String phone) {
//        1.生成验证
        String code = GeneratorCode.getCode(6);
//        2.发送验证码到手机号
        try {
            this.smsTemplate.sendSms(phone, code);
        } catch (ClientException e) {
            e.printStackTrace();
        }
//        3.并且缓存中存入一份手机号
        this.redisTemplate.opsForValue().set(PREFIX, code, 5, TimeUnit.MINUTES);
    }


}
